<?php
class RpcController
{
    private $userModel;
    private $autoUidModel;
    private $userMemberModel;
    private $userStatisticsModel;
    private $diaryListCacheModel;
    private $diaryListModel;
    private $topicModel;
    private $likeModel;
    private $groupInfoModel;
    private $diaryAttachmentModel;
    private $diaryBodyModel;
    private $userLoginModel;
    private $tokenUserModel;
	private $messageBoxModel;
    private $messageService;
	private $articleService;
	private $diaryService;
	private $chatGroupService;

    function __construct()/*{{{*/
    {
        $this->userModel            =   new UserModel();
        $this->autoUidModel         =   new AutoUidModel();
        $this->userMemberModel      =   new UserMemberModel();
        $this->userStatisticsModel  =   new UserStatisticsModel();
        $this->diaryListCacheModel  =   new DiaryListCacheModel();
        $this->diaryListModel       =   new DiaryListModel();
        $this->topicModel          	=   new TopicModel();
        $this->likeModel            =   new LikeModel();
        $this->groupInfoModel       =   new GroupInfoModel();
        $this->diaryAttachmentModel =   new DiaryAttachmentModel();
        $this->diaryBodyModel       =   new DiaryBodyModel();
        $this->userLoginModel       =   new UserLoginModel();
        $this->tokenUserModel       =   new TokenUserCacheModel();
		$this->messageBoxModel      =   new MessageBoxModel();
        $this->messageService       =   new MessageService();
		$this->articleService       =   new ArticleService();
		$this->diaryService         =   new DiaryService();
		$this->chatGroupService     =   new ChatGroupService();
    }/*}}}*/

    public function sendPrizeMsg($param)
	{
		$gift     = array(
			'a'=>'kindle',
			'b'=>'充电宝',
			'c'=>'创意文具',
			'd'=>'卡西欧函数计算器',
			'e'=>'手帐记事本',
			'f'=>'零食大礼包',
			'g'=>'惊喜神秘大奖',
			'h'=>'粉粉1个月试用会员',
			'i'=>'谢谢参与',
		);
		$uid = $param['uid'];
		$tag = $param['tag'];
		if(empty($uid) || empty($tag)){
			return false;
		}
		$msg = '恭喜你在【粉粉贺卡送祝福】活动中抽到'.$gift[$tag].'！活动结束后10个工作日内，粉粉日记工作人员将主动联系您并安排奖品寄送，请保持粉粉日记APP在线及联系电话畅通~';
		$content = $msg;
		if($tag=='h'){
			$content = '恭喜你在【粉粉贺卡送祝福】活动中抽到粉粉1个月试用会员啦！即刻体验酷炫到没朋友的会员专享福利吧！';
		}
		if (!$gift[$tag]){
			return false;
		}

		$user = $this->autoUidModel->getUserInfo($uid);
		if(!$user){
			return false;
		}
		$nickname = $user['nickname'] ? $user['nickname'] : '粉粉用户';
		$param = array(
			'uid'      => '1',
			'mUid'     => $uid,
			'nickname' => '粉粉小秘书',
			'mNickname'=> $nickname,
			'content'  => $content,
		);
        //$this->messageBoxModel->sendMessage($param);
		$this->messageService->sendMessage($param['uid'], $param['mUid'], $param);
	}

    public function sendCode($param){
		if(!UK::isMobile($param['mobile'])){
			return false;
		}
		$info = array(
			'appname'=>'粉粉日记',
			'mobile' => strval($param['mobile']),
			'type'   => 'mobile_signin',
		);
		$controller = new UserController();
		$result=$controller->getMobileCode($info);
		return $result;
	}

	public function loginByCode($param){
		if(!UK::isMobile($param['mobile']) || strlen($param['code']) < 1){
			return false;
		}

		$phone              =   $param['mobile'];
		$code               =   $param['code'];
		$register_type      =   UK::getMobileCodeType('mobile_signin');
		$mobileCodeIsValid  =   $this->autoUidModel->checkMobileCodeIsValid($phone, $code, $register_type);
		if (AC::$errorNo) return false;

		$account    =   'mobile-'.$phone;
		$userInfo   =   $this->userLoginModel->getUserInfoByAccount($account);
		$result     =   $this->autoUidModel->getUserInfo($userInfo['uid']);

		return $result;
	}

    public function getUidByOpenUid($param){
        $openUid   = trim($param['openUid']);
        $openToken = trim($param['openToken']);
        $platform  = trim($param['platform']);
        if (empty($openUid) || empty($openToken)  ||  empty($platform) || !in_array($platform, AC::$openTypes))
        {
            AC::$errorNo    =   'UC018';
            return  FALSE;
        }

        $openUser   =   UK::getThirdPartyUser($platform, $openUid);
        $result = $this->userLoginModel->getUserInfoByAccount($openUser);
        if (empty($result) || empty($result['account'])) {
            return (Object) array();
        }

        return array('uid' => $result['uid']);
    }

    public function checkUserLogin ($param) {

        list($account, $password, $send_time, $sign, $third_id) = $this->filterCheckUserLoginParams($param);
        if (strlen($account) < 1 || strlen($password) < 1) {
            AC::$errorNo    =   'RPC001';
            AC::$errorMsg   =   '账号或密码不能为空';
            return  false;
        }

        $check = $this->checkSignValied($sign, $account, $third_id, $send_time, $password);
        if (empty($check)) {
            AC::$errorNo    =   'RPC002';
            AC::$errorMsg   =   '签名验证失败';
            return  false;
        }

        $user = $this->simplyLogin($account, $password);
        if (empty($user)) {
            AC::$errorNo    =   'RPC003';
            AC::$errorMsg   =   '密码或账号错误';
            return  false;
        }

        return $user;
    }

    private function filterCheckUserLoginParams($param) {
        $account    = strlen($param['account']) > 0 ? strval($param['account']) : '';
        $password   = strlen($param['password']) > 0 ? strval($param['password']) : '';
        $send_time  = intval($param['time']);
        $sign       = isset($param['sign']) ? strval($param['sign']) : '';
        $third_id   = strlen($param['third_id']) > 0 ? strval($param['third_id']) : '';

        return array($account, $password, $send_time, $sign, $third_id);
    }

    private function checkSignValied($sign, $account, $third_id, $send_time, $password) {
        $gsign = '';
        if ($third_id) {
            $gsign = sha1($account.$third_id.$send_time);
        }else{
            $gsign = sha1($account.$password.$send_time);
        }

        return $gsign == $sign ? true : false;
    }

    private function simplyLogin($account, $passwd) {
        $param = array('account' => $account, 'passwd' => $passwd);

        if (UK::isMobile($account)) {
            $param['account'] = UK::getMobileUser($account);
            $result =   $this->userLoginModel->userLogin($param);
            if (empty($result)) {
                list($login_type, $area, $param['account']) = explode('-', $param['account']);
                $result =   $this->userLoginModel->userLogin($param);
            }
        }elseif(UK::isFenFenId($account)){
            $result =   $this->userLoginByUid($account, $passwd);
        }else{
            $result =   $this->userLoginModel->userLogin($param);
        }
        if (empty($result['uid'])) return false;

        $user  = $this->autoUidModel->getUserInfo($result['uid']);
        if (empty($user['uid'])) return false;

        return  $user;
    }

    private function userLoginByUid($uid,$passwd){
        $autoUidInfo = $this->autoUidModel->getUserBaseInfo(array('uid'=>$uid));
        if(!$autoUidInfo || !$autoUidInfo['account'] || !$autoUidInfo['platform']){
            AC::$errorNo = 'UCL002';
            return false;
        }

        $account ='';
        $password = '';
        if($autoUidInfo['platform'] == 'ffrj') {
            $account = $autoUidInfo['account'];
            $password = $passwd;
        }else{
            $userconnectInfo = $this->userModel->getUserConnnets($uid);
            if($userconnectInfo){
                foreach($userconnectInfo as $info){
                    if($info['open_type'] == AC::$accountTypeConfig['mobile'] || $info['open_type'] == AC::$accountTypeConfig['fenfen']){
                        $account = $info['open_id'];
                        $password = $passwd;
                    }
                }
            }
        }

        if(!$account || !$password){
            AC::$errorNo = 'UCL003';
            return false;
        }

        $userLoginParam = array('account'=>$account,'passwd'=>$password);
        $result = $this->userLoginModel->userLogin($userLoginParam);
        return $result;
    }

    /**
     * 手机号注册
     * @param $param
     * @return array|bool
     */
    public function registerByMobile($param) {
        $account = strval($param['account']);
        $passwd  = strval($param['password']);
        $code    = strval($param['code']);
        $registerChannel = isset($param['registerChannel']) ? intval($param['registerChannel']) : 30; // 30:粉粉钱包, 60:粉粉手账
        if (empty($account) ||  empty($passwd) || empty($code)) {
            AC::$errorNo    =   'RPC001';
            return  false;
        }

        if (!UK::isMobile($account)) {
            AC::$errorNo    =   'RPC004';
            return false;
        }

        return $this->registerUser($account, $passwd, $code, $registerChannel);
    }

    private function registerUser($account, $passwd, $code, $registerChannel = '') {
        $register_type = UK::getMobileCodeType('mobile_register');
        $mobileCodeIsValid = $this->autoUidModel->checkMobileCodeIsValid($account, $code, $register_type);
        if (AC::$errorNo) {
            return false;
        }

        $param     = array(
            'account'   => UK::getMobileUser($account),
            'email'     => '@ffrj@'. $account,
            'nickname'  => '粉粉用户',
            'type'      =>  $register_type,
            'passwd'    =>  $passwd,
            'registerChannel'   =>  $registerChannel
        );

        $uid    =   $this->autoUidModel->initAutoUid($param);
        if (empty($uid)) {
            return  false;
        }

        $param['uid']    =   $uid;
        if ("粉粉用户" === $param['nickname']) $param['nickname'] .= $uid;
        $result = $this->initUser($param);
        if (empty($result)) {
            UK::varDump(AC::$errorNo, __METHOD__);
            return false;
        }

        $token = $this->makeUserToken($uid, 'registerUser');
        return  array('uid' =>  strval($uid), 'token' => $token);
    }

    public function checkMobileCode($param)
    {
        $param['mobile'] = $param['phone'];
        $param['type']  = (isset($param['type']) && $param['type']) ? $param['type'] : 'mobile_register';
        
        $userController = new UserController();
        $result = $userController->checkMobileCode($param);
        return $result;
    }

    private function initUser($param)
    {
        $initUserLogin      =   $this->userLoginModel->initUserLogin($param);
        if (empty($initUserLogin)) {
            AC::$errorNo    =   'RPC007';
            return false;
        }

        $initUserStatistics =   $this->userStatisticsModel->initUserStatistics($param);
        if (empty($initUserStatistics)) {
            AC::$errorNo    =   'RPC008';
            return false;
        }

        $initUserMember     =   $this->userMemberModel->initUserMember($param);
        if (empty($initUserMember)) {
            AC::$errorNo    =   'RPC009';
            return false;
        }

        $registerUser       =   $this->userModel->registerUser($param);
        if (empty($registerUser)) {
            AC::$errorNo    =   'RPC010';
            return false;
        }

        return true;
    }

    public function sendCodeByMobile($param) {
        $mobile = strval($param['phone']);
        $type   = strval($param['type']);
        if (empty($mobile) || empty($type)) {
            AC::$errorNo    =   'RPC001';
            return false;
        }

        $param['mobile'] = $param['phone'];
        $param['appname'] = '可萌记账';
        $userController = new UserController();
        $result = $userController->getMobileCode($param);

        return $result;
    }

    /**
     * 发送验证码
     * @param $param
     * @return bool
     */
    public function sendSms($param)
    {
        $uid    = intval($param['uid']) ? intval($param['uid']) : 0;
        $mobile = strval($param['mobile']) ? trim(strval($param['mobile'])) : '';
        $type   = strval($param['type']) ? trim(strval($param['type'])) : '';
        $code   = strval($param['sms_code']) ? trim(strval($param['sms_code'])) : '';
        $content= strval($param['content']) ? trim(strval($param['content'])) : '';
        $appName= strval($param['appName']) ? trim(strval($param['appName'])) : '可萌记账';
        $ip     = strval($param['ip']) ? strval($param['ip']) : '127.0.0.1';
        if (empty($mobile) || empty($type) || strlen($code) < 6 || strlen($content) < 10) {
            AC::$errorNo    =   'RPC001';
            return false;
        }

        $smsService = new SmsService($uid, $mobile, $code, $type, $ip, $content, $appName);
        return $smsService->sendMobileCode();
    }

    public function modifyMobileLoginPasswd($param) {
        $mobile = strval($param['phone']);
        $passwd = strval($param['password']);
        $code   = strval($param['code']);
        if (empty($mobile) || empty($code) || empty($passwd)) {
            AC::$errorNo    =   'RPC001';
            return false;
        }

        $param['mobile'] = $param['phone'];
        $param['passwd'] = $param['password'];
        $userController = new UserController();
        $result = $userController->modifyMobileLoginPasswd($param);

        return $result;
    }

    public function updateLoginPasswd($param) {
        $uid        = strval($param['uid']);
        $newPasswd  = strval($param['newPassword']);
        $oldPasswd  = strval($param['oldPassword']);
        if (empty($uid) || empty($newPasswd) || empty($oldPasswd)) {
            AC::$errorNo    =   'RPC001';
            return false;
        }

        $userController = new UserController();
        $result = $userController->updateUserPassword($uid, $newPasswd, $oldPasswd);

        return $result;
    }

    public function checkPasswdIsValid($param) {
        $uid        = strval($param['uid']);
        $oldPasswd  = strval($param['oldPassword']);
        if (empty($uid) || empty($oldPasswd) || strlen($oldPasswd) < 32) {
            AC::$errorNo    =   'RPC001';
            return false;
        }

        $userController = new UserController();
        $result = $userController->checkPasswdIsValid($uid, $oldPasswd);

        return $result;
    }

    private function makeUserToken($uid, $do)
    {
        $param = array('uid' => $uid, 'do' => $do);
        $result =   $this->tokenUserModel->makeUserToken($param);
        return  $result;
    }

    public function changeExpLevel($userInfo)
    {
        if (empty($userInfo['uid']))
        {
            AC::$errorNo    =   'UC011';
            return  FALSE;
        }
         
        $user         =  $this->userMemberModel->getMemberInfo($userInfo);
        if (empty($user)){
            AC::$errorNo    =   'UC023';
            return  FALSE;
        }

        //会员经验加成
//        $vip_info = $this->autoUidModel->getUserVipInfo($userInfo['uid']);
//        if ($vip_info){
//            $user['exp'] = intval($user['exp']);
//            if ($vip_info['is_year_vip']){//年费会员加成1.5倍
//                $user['exp'] = ceil($user['exp'] * AC::VIP_YEAR_EXP_ADDED_TIMES);
//            }else{//普通会员加成1.2倍
//                $user['exp'] = ceil($user['exp'] * AC::VIP_EXP_ADDED_TIMES);
//            }
//        }
         
        // 计数用户等级经验值计数
        $userInfo['level'] = intval($user['level']);
        $userInfo['exp']   = intval($user['exp']) + intval($userInfo['exp']);
    
        $total = array();
        $total = ExpLevel::$levelNeedExp;
    
        //系统设定的总的经验值设定
        $totalExp = '';
        foreach ($total as $val)
        {
            $totalExp += $val;
        }
    
        //传过来的经验值和等级，计算出总的经验值
        $changedTotalExp = '';
        for($i=1;$i<$userInfo['level'];$i++)
        {
            $changedTotalExp += ExpLevel::$levelNeedExp[$i];
        }
        $changedTotalExp	+=	$userInfo['exp'];
    
        //不能超过系统设定的总经验值
        if ($changedTotalExp > $totalExp) return false;

        for($i=1;$i<=count($total);$i++)
        {
            $changedTotalExp -= $total[$i];
            if($changedTotalExp <0)
            {
                $level = $i;
                $exp   = $changedTotalExp+$total[$i];
                break;
            }
        }
    
        $data['level'] =  $level;
        $data['exp']   =  $exp;
        $data['uid']   =  $userInfo['uid'];
        $this->diaryListCacheModel->delUserCache($userInfo['uid']);
    	$result        =  $this->userMemberModel->changeExpLevel($data);
    	if (empty($result)) return false;
    	return  TRUE;
    }
    
    /**
     * 任务接口
     * @param unknown $param
     * @return multitype:string multitype: boolean |boolean|multitype:string multitype: boolean Ambigous <multitype:, string, multitype:multitype:string  >
     */
    public function doTask ($param) {
        $result = array(
            'uid'        =>    strval($param['uid']),
            'task'       =>    '',
            'gainCoin'   =>    '0',
            'conditions' =>    array(),
            'is_complete'=>    FALSE
        );
        
        $tasks_no_check    = array('share', 'system_award');
        $tasks_must_check  = array('perfect_information', 'freshman_reward', 'daily_write_reward', 'ability_monthly_award');
        if (!in_array($param['task'], $tasks_no_check) && !in_array($param['task'], $tasks_must_check)){
            return $result;
        }
        
        $result['task'] = strval($param['task']);
        // 直接加金币
        if (in_array($param['task'], $tasks_no_check)){
            $api = NULL;
            $coinTask = '';
            $amount = 0;
            $remark = '';
            // 任务_分享
            if ($param['task'] == 'share'){
                $coinTask = MallApi::$task_share;
                $api = UK::getMallApi($param['adminUid']);
            }
        
            // 话题加精
            if ($param['task'] == 'topic_elite'){
                $coinTask = MallApi::$task_topic_elite;
                $api = UK::getMallApi($param['adminUid']);
            }
        
            // 后台加粉币
            if ($param['task'] == 'system_award'){
                $amount = intval($param['coin']);
                if ($amount < 1) {
                    return FALSE;
                }
        
                if ($amount >= 50) {
                    $amount = 50;
                }
        
                $remark = $_SERVER['SERVER_NAME'].'_'.$param['mUid']."_".$param['adminUid'];
                $coinTask = MallApi::$task_system_award;
                if (!empty($param['mUid'])){
                    $api = UK::getMallApi($param['mUid']);
                }
            }
        
            if (empty($api)){
                return FALSE;
            }
        
            // 加金币
            $coin = $api->executeCoinTask($coinTask, $amount, $remark);
            if ($coin && $coin['change'] > 0){
                $result['gainCoin'] = strval($coin['change']);
                $result['is_complete'] = TRUE;
            }
        }
        
        // 条件判断
        if (in_array($param['task'], $tasks_must_check)){
            // 任务_完善个人资料
            if ($param['task'] == 'perfect_information'){
                $info       =   $this->checkUserInfoIsPerfected($param['uid']);
            }
        
            // 任务_新手大礼包
            if ($param['task'] == 'freshman_reward'){
                $info       =   $this->checkUserNovicePackage($param['uid']);
            }
        
            // 任务_每日一记
            if ($param['task'] == 'daily_write_reward'){
                $info       =   $this->checkDailyRecord($param['uid']);
            }
        
            // 达人领奖励
            if ($param['task'] == 'ability_monthly_award') {
                $info       =   $this->checkAbility($param['uid']);
            }
        
            // 返回判断条件列表
            $result['conditions'] = $info;
        
            // 判断任务是否完成
            $check_result = 1;
            foreach ($info as $value){
                $check_result *= intval($value['result']);
            }
            if ($check_result){
                $result['is_complete'] = TRUE;
            }
        }
        
        return  $result;
    }
    
    /**
     * 判断是否完善资料
     * @return Ambigous <number, multitype:multitype:string number  >
     */
    public function checkUserInfoIsPerfected($uid){
        $result = array(
                array('name' => 'check_avatar',    'info' => '上传清晰头像',  'result' => '0'),
                array('name' => 'check_nickname',  'info' => '设置昵称',     'result' => '0'),
                array('name' => 'check_signature', 'info' => '设置签名',     'result' => '0'),
                array('name' => 'check_city',      'info' => '设置城市地点',  'result' => '0'),
                array('name' => 'check_birthday',  'info' => '设置星座',     'result' => '0'),
                array('name' => 'check_tagset',    'info' => '设置标签',     'result' => '0'),
        );
    
        $userController = new UserController();
        $userInfo = $userController->getUserInfo(array('uid' => $uid));
        if (AC::$errorNo){
            AC::$errorNo = NULL;
        }
    
        // 判断高清头像
        $avatar      = UK::getuseravatarurl($uid);
        $uavatar     = $userInfo['userInfo']['avatar'];
        $pre_avatar  = substr($avatar, 0, -strlen(strstr($avatar,'?')));
        $pre_uavatar = substr($uavatar, 0, -strlen(strstr($uavatar,'?')));
    
        if (!empty($userInfo['userInfo']['photos']) || ($pre_avatar != $pre_uavatar)){
            $result[0]['result'] = '1';
        }
    
        // 判断昵称
        if ($userInfo['userInfo']['nickname'] != '粉粉用户'.$uid && $userInfo['userInfo']['nickname'] != '未设置昵称'){
            $result[1]['result'] = '1';
        }
    
        // 判断签名
        if (!empty($userInfo['userInfo']['signature'])){
            $result[2]['result'] = '1';
        }
    
        // 判断城市
        if (!empty($userInfo['userInfo']['city'])){
            $result[3]['result'] = '1';
        }
    
        // 判断星座
        if (!empty($userInfo['userInfo']['birthday'])){
            $result[4]['result'] = '1';
        }
    
        // 判断标签
        if (!empty($userInfo['userInfo']['tag_list'])){
            $result[5]['result'] = '1';
        }
    
        return $result;
    }
    
    /**
     * 新手大礼包任务
     * @return Ambigous <number, multitype:multitype:string number  >
     */
    public function checkUserNovicePackage($uid){
        $result = array(
                array('name' => 'check_follows',    'info' => '关注20个用户',    'result' => '0'),
                array('name' => 'check_fans',       'info' => '拥有10位粉丝',      'result' => '0'),
                array('name' => 'check_diarytimes', 'info' => '发布两篇公开日记',  'result' => '0'),
                array('name' => 'check_topictimes', 'info' => '发布两篇话题',     'result' => '0'),
        );
    
        $userController = new UserController();
        $userInfo = $userController->getUserInfo(array('uid' => $uid));
        if (AC::$errorNo){
            AC::$errorNo = NULL;
        }
    
        // 判断关注数
        if ($userInfo['userStatistics']['meFollowTimes'] >= 20){
            $result[0]['result'] = '1';
        }
    
        // 判断粉丝数
        if ($userInfo['userStatistics']['followMeTimes'] >= 10){
            $result[1]['result'] = '1';
        }
    
        // 判断开日记数
        if ($userInfo['userStatistics']['diaryTimes'] >= 2){
            $result[2]['result'] = '1';
        }
    
        // 判断话题数
        if ($userInfo['userStatistics']['topicTimes'] >= 2){
            $result[3]['result'] = '1';
        }
    
        return $result;
    }
    
    /**
     * 每日一记任务
     * @param unknown $uid
     * @return Ambigous <string, multitype:multitype:string  >
     */
    public function checkDailyRecord ($uid) {
        $result = array(
                array('name' => 'check_daily_diary',    'info' => '今日发布1篇日记',    'result' => '0'),
                array('name' => 'check_daily_topic',    'info' => '今日发布1篇话题',    'result' => '0')
        );
    
        // 获取用户最新一篇日记
        $diaryList = $this->diaryListModel->getLastestDiary($uid);
    
        // 判断今日是否发布了日记
        if (!empty($diaryList)){
            $isToday = UK::isToday($diaryList[0]['time']);
            if ($isToday) {
                $result[0]['result'] = '1';
            }
        }
    
        // 获取用户最新一篇话题
        $topicList = $this->topicModel->getLastestTopic($uid);
    
        // 判断今日是否发布了话题
        if (!empty($topicList)){
            $isToday = UK::isToday($topicList[0]['time']);
            if ($isToday) {
                $result[1]['result'] = '1';
            }
        }
    
        if (AC::$errorNo) {
            AC::$errorNo = NULL;
        }
    
        return $result;
    }
    
    public function checkAbility ($uid) {
        $result = array(
                array('name' => 'check_monthly_diary',    'info' => '每月发布20篇点滴',    'result' => '0'),
                array('name' => 'check_monthly_topic',    'info' => '每月发布10篇话题',    'result' => '0')
        );
    
        $userController = new UserController();
        $userInfo = $userController->getUserInfo(array('uid' => $uid));
        if (AC::$errorNo){
            AC::$errorNo = NULL;
        }
    
        // 判断达人
        if (empty($userInfo['userInfo']['is_ability'])){
            return $result;
        }
    
        // 获取用户最新20篇日记
        $diaryList = $this->diaryListModel->getLastestDiary($uid, 0, 20);
    
        // 判断今日是否发布了日记
        if (!empty($diaryList)){
            $time = 0;
            foreach ($diaryList as $value) {
                $time = $value['time'];
            }
            $isCurrentMonth = UK::isCurrentMonth($time);
            if ($isCurrentMonth) {
                $result[0]['result'] = '1';
            }
        }
    
        // 获取用户最新10篇话题
        $topicList = $this->topicModel->getLastestTopic($uid, 0, 10);
        // 判断今日是否发布了话题
        if (!empty($topicList)){
            $time = 0;
            foreach ($diaryList as $value) {
                $time = $value['time'];
            }
            $isCurrentMonth = UK::isCurrentMonth($time);
            if ($isCurrentMonth) {
                $result[1]['result'] = '1';
            }
        }
    
        if (AC::$errorNo) {
            AC::$errorNo = NULL;
        }
    
        return $result;
    }
    
    /**
     * 获取用户缓存信息
     * @param unknown $param
     * @return boolean|StdClass|Ambigous
     */
    public function getUserInfo ($param) {
        $uid = intval($param['uid']);
        if ($uid < 1) {
            return FALSE;
        }
        
        // 获取用户缓存信息
        $user_cache = $this->diaryListCacheModel->getUserCache($uid);
        if (empty($user_cache)) {
            return FALSE;
        }
        $user_cache['avatar']      =    UK::getuseravatarurl($uid, $user_cache['avatar']);
        $result = array(
            'userInfo'  =>  $user_cache,
            'userMember'=>  (Object) array(),
            'userStatictics'=>  (Object) array()
        );
        return $result;
    }

    public function getUserService ($param) {
        $uid = intval($param['uid']);
        if ($uid < 1) {
            return FALSE;
        }

        $service = new UserService();
        $result = $service->getUserInfo($uid, 0);
        return $result;
    }
    
    public function getUserDetail ($param) {
        $uid = intval($param['uid']);
        if ($uid < 1) {
            return FALSE;
        }
        
        $userController = new UserController();
        $userInfo = $userController->getUserInfo(array('uid' => $uid));
        if (AC::$errorNo){
            AC::$errorNo = NULL;
        }
        return $userInfo;
    }
    
    /**
     * 获取群组信息
     * @param unknown $param
     * @return boolean|StdClass|Ambigous <multitype:string , multitype:, string, Ambigous>
     */
    public function getChatGroupInfo ($param) {
        $gid = intval($param['gid']);
        if ($gid < 1) {
            return FALSE;
        }
        
        $chat_group_info = $this->likeModel->getChatGroupInfoByGid($gid);
        if (empty($chat_group_info)) {
            return FALSE;
        }
        
        // 群中的用户列表
        $chat_group_info['userlist'] = $tmp = array();
        $uidsArr = $this->diaryListCacheModel->getChatGroupUsersList($gid, 0, 8);
        if ($uidsArr){
            foreach ($uidsArr as $value){
                $tmp = $this->autoUidModel->getUserInfo($value);
                $tmp = $this->autoUidModel->checkIsMe($tmp);
                $tmp['nickname']    =    $this->autoUidModel->getRemarkName($tmp);
                $chat_group_info['userlist']['users'][] = $tmp;
            }
            $chat_group_info['userlist']['counts'] = count($chat_group_info['userlist']['users']);
        }
        return $chat_group_info;
    }
    
    /**
     * 获取话题信息
     * @param unknown $param
     * @return boolean|Ambigous <multitype:, NULL, string, mixed>
     */
    public function getTopicInfo ($param) {
        $tid = intval($param['tid']);
        if ($tid < 1) {
            return FALSE;
        }
        
        $topic_info      =   $this->topicModel->topicAddRedis(array('tid' => $tid));
        if (empty($topic_info)){
            return FALSE;
        }

        $topic  = 	$this->topicData($topic_info);
        $result = array('topic_info'    =>  $topic);
        
        return $result;
    }
    
    private function topicData ($info) {
        $data = array();
        $data['id']			    = intval($info['id'])  > 0           ? strval($info['id'])  : '0';
        $data['tid']			= intval($info['tid']) > 0           ? strval($info['tid']) : '0';
        $data['uid']			= intval($info['uid']) > 0           ? strval($info['uid']) : '0';
        $data['gid']			= intval($info['gid']) > 0           ? strval($info['gid']) : '0';
        $data['gname']			= !empty($info['gname'])             ? strval($info['gname']) : '';
        $data['title']			= !empty($info['title'])             ? strval($info['title']) : '';
        $data['content']		= !empty($info['abbreviation'])      ? strval($info['abbreviation']) : '';
        $data['category']		= intval($info['category'])  > 0     ? strval($info['category']) : '0';
        $data['highlight']		= intval($info['highlight']) > 0     ? strval($info['highlight']): '0';
        $data['fav_num']		= intval($info['favtimes'])  > 0     ? strval($info['favtimes']) : '0';
        $data['share_num']		= intval($info['sharetimes']) > 0    ? strval($info['sharetimes']) : '0';
        $data['view_num']		= intval($info['view_num']) > 0      ? strval($info['view_num']): '0';
        $data['res_num']		= intval($info['response_num'])  > 0 ? strval($info['response_num']) : '0';
        $data['recom_num']		= intval($info['recom_num'])  > 0    ? strval($info['recom_num']) : '0';
        $data['is_today']		= "0";
        $data['display']		= intval($info['display'])  > 0      ? strval($info['display']) : '0';
        $data['digest']			= intval($info['digest'])  > 0       ? strval($info['digest']) : '0';
        $data['time']			= intval($info['time'])  > 0         ? strval($info['time']) : '0';
        $data['status']			= intval($info['status'])  > 0       ? strval($info['status']) : '0';
        $data['last_reply']		= intval($info['last_reply'])  > 0   ? strval($info['last_reply']) : '0';
        $data['last_uid']		= intval($info['last_reply_uid'])  > 0 ? strval($info['last_reply_uid']) : '0';
        $data['last_user']		= !empty($info['last_reply_username']) ? strval($info['last_reply_username']) : '';
        $data['is_favor'] 		= '0';
        $data['recommend']      = intval($info['recommend'])  > 0      ? strval($info['recommend']) : '0';
        $data['attachments']    = array();
        $data['voiceList']      = array();
        
        $user			            = $this->autoUidModel->getUserInfo($info['uid']);
        $data['user']           	= $this->autoUidModel->checkIsMe($user);
        $data['user']['nickname']   = $this->autoUidModel->getRemarkName($data['user']);
        return $data;
    }
    
    /**
     * 获取日记详情
     * @param unknown $param
     * @return boolean|multitype:multitype: Ambigous <> unknown Ambigous Ambigous <NULL, boolean, multitype:, unknown>
     */
    public function getDiaryInfo($param){
        $bodyId     =   intval($param['bodyId']);
        if ($bodyId < 1) {
            return FALSE;
        }
        
        $listInfo   =   $this->diaryListModel->getDiaryListInfoByBodyId($bodyId);
        if (empty($listInfo)){
            return  FALSE;
        }
        $author_uid = $listInfo['uid'];
    
        $attachmentList =   array();
        if (!empty($listInfo['attachmentPath'])){
            $attachmentList =   $this->diaryAttachmentModel->getDiaryAllAttachment($param);
        }
    
        $bodyInfo   =   $this->diaryBodyModel->getDiaryBody($author_uid, $param['bodyId']);
        if (!empty(AC::$errorNo)){
            return  FALSE;
        }
    
        $user = $this->autoUidModel->getUserInfo($author_uid);

        $geo = array();
        return  array('bodyInfo' => $bodyInfo, 'attachment' => $attachmentList['attachmentList'], 'voiceList'=>$attachmentList['voiceList'], 'listInfo' => $listInfo,'userInfo'=> $user,'geo' => $geo);
    }

    /**
     * 获取文章详情（RPC）
     * @param $param
     * @return array|bool
     */
    public function getArticleData($param)
    {
        $author_uid        =   intval($param['uid']);
        $articleBodyId     =   intval($param['bodyId']);
        if ($articleBodyId < 1) {
            AC::$errorNo    =   'ATC001';
            return  FALSE;
        }

        $articleService = new ArticleService();
        $articleInfo   = $articleService->getArticleInfo($articleBodyId, $author_uid, '', 1);
        if (AC::$errorNo) {
            return  FALSE;
        }

        return $articleInfo;
    }

    /**
     * 更新用户流量信息
     * @param unknown $param
     * @return boolean
     */
    public function updateUserTraffic ($param) {
        $uid     = intval($param['uid']);
        $traffic = intval($param['traffic']);
        if (empty($uid) || empty($traffic)) {
            return FALSE;
        }
        
        $user = $this->autoUidModel->getUserInfo($uid);
        if (empty($user)) {
            return false;
        }
        
        $traffic = abs(floor($traffic) * 1024);
        $result  = $this->userMemberModel->updateUserTraffic($uid, $traffic);
        if (!$result) return false;
        
        return true;
    }

    public function clientLog($param){
        $param['client'] = UK::getstr($param['client'], 5000);
        $param['logpath'] = UK::getstr($param['logpath'], 1000);
        $param['uid'] = isset($param['uid']) ? ( intval($param['uid'])>0 ? intval($param['uid']) : 0 ) : 0;
        $param['type'] = isset($param['type']) ? ( intval($param['type'])>0 ? intval($param['type']) : 0 ) : 0;
        if (empty($param['client']) || empty($param['logpath'])){
            return true;
        }
        $rpcModel = new RpcModel();
        $result = $rpcModel->addClientlog($param);
        return $result ? true : false;
    }

    public function sendMsgToUser($param){
        $uid = isset($param['fuid']) ? intval($param['fuid']) : 1;
        $mUid = isset($param['uid']) ? intval($param['uid']) : 0;
        $content = isset($param['content']) ? trim($param['content']) : '';
        $data = [];
        if ($mUid<1 || empty($content))return false;
        isset($param['mNickname']) && $param['mNickname']      && $data['mNickname'] = $param['mNickname'];
        isset($param['nickname'])  && $param['nickname']       && $data['nickname'] = $param['nickname'];
        isset($param['msgType'])   && $param['msgType']        && $data['msgType'] = $param['msgType'];
        isset($data['msgType'])    && isset($param['msgData']) && $param['msgData'] && $data['msgData'] = UK::var_json_encode(json_decode($param['msgData'], true));
        $data['content'] = $content;
        $messageService = new MessageService();
        return $messageService->sendMessage($uid, $mUid, $data);
    }

    public function reviewDiary($param){
        $logs = 'reviewDiary.log';
        UK::saveLog($logs, date('Y-m-d H:i:s').':start~~~:'."\n");
        UK::saveLog($logs, date('Y-m-d H:i:s').':param:'.json_encode($param)."\n");
        $bodyId = isset($param['bodyId']) ? trim($param['bodyId']) : 0;
        $review_result = isset($param['status']) ? intval($param['status']) : -1; //1-不合格,2-合格
        $rate = isset($param['rate']) ? intval($param['rate']) : 50; //进度
        if ($bodyId<1 || $review_result<1 || $review_result>2)
            return ;
        $diaryReviewService = DiaryReviewService::getInstance();
        switch ($review_result){
            case 1://不合格
                $diaryReviewService->reviewNotPass($bodyId);
                break;
            case 2://合格
                $diaryReviewService->reviewPass($bodyId);
                break;
        }
        UK::saveLog($logs, date('Y-m-d H:i:s').':result:'.print_r('end~~~', true)."\n\n\n");
        return true;
    }

    public function addPreVipUser($param){
        $logs = 'addPreVipUser.log';
        UK::saveLog($logs, date('Y-m-d H:i:s').':param:'.json_encode($param)."\n");
        $uid = isset($param['uid']) ? intval($param['uid']) : 0;
        $day = isset($param['day']) ? intval($param['day']) : 0;
        if ($uid<1 && $day<1 && $day>366){
            AC::$errorNo = 'VIP001';
            return false;
        }
        //检查该用户存不存在
        $user = $this->autoUidModel->getUserInfo($uid);
        if (empty($user)){
            AC::$errorNo = 'VIP001';
            return false;
        }
        $vip_info = $this->autoUidModel->getUserVipInfo($uid);
        $end_time = AC::SERVER_TIME + ($day*3600*24);
        if ($vip_info){
            $end_time = $vip_info['end_time'] + ($day*3600*24);
        };
        $new = [
            'end_time' => $end_time, 'type' => 2//试用
        ];
        $day>360 && $new['yearvip_end_time'] = $end_time;//年费会员
        if ($vip_info){
            //续费操作
            UK::saveLog($logs, date('Y-m-d H:i:s').':update:'.json_encode($new)."\n");
            $result = $this->autoUidModel->updateUserVipInfo($new, $uid);
        }else{
            //首次开通
            UK::saveLog($logs, date('Y-m-d H:i:s').':create:'.json_encode($new)."\n");
            $result = $this->autoUidModel->addUserVip($new, $uid);
        }
        if ($result){
            $result = $this->userModel->updateUserInfo(['uid'=>$uid], ['vip'=>$end_time], $uid);
            $result && $this->diaryListCacheModel->delUserCache($uid);
            if (empty($vip_info)){
                //首次增加会员流量
                $traffic = 200 * 1024;
                $trc_res = $this->userMemberModel->updateUserVipTraffic($uid, $traffic);
                $trc_res && UK::saveLog($logs, date('Y-m-d H:i:s').':traffic:'.$traffic."\n");
            }
        }
        UK::saveLog($logs, date('Y-m-d H:i:s').':result:'.$result."\n");
        return $result ? true : false;
    }

    public function addVipUser($param){
        $logs = 'addVipUser.log';
        UK::saveLog($logs, date('Y-m-d H:i:s').':param:'.json_encode($param)."\n");
        $uid = isset($param['uid']) ? intval($param['uid']) : 0;
        $month = isset($param['month']) ? intval($param['month']) : 0;
        $addDay = isset($param['add_day']) ? intval($param['add_day']) : 0;
        if ($uid<1 && $month<1 && $month>12){
            AC::$errorNo = 'VIP001';
            return false;
        }
        //检查该用户存不存在
        $user = $this->autoUidModel->getUserInfo($uid);
        if (empty($user)){
            AC::$errorNo = 'VIP001';
            return false;
        }
        //首次购买会员
        $now_month = date('n', AC::SERVER_TIME);
        $end_year = date('Y', AC::SERVER_TIME);
        $end_day = date('j', AC::SERVER_TIME);
        $end_time = date('H:i:s', AC::SERVER_TIME);
        $vip_info = $this->autoUidModel->getUserVipInfo($uid);
        if ($vip_info){
            //续费
            $vip_end_time = $vip_info['end_time'];
            $now_month = date('n', $vip_end_time);
            $end_year = date('Y', $vip_end_time);
            $end_day = date('j', $vip_end_time);
        }

        $end_month = $month + $now_month;
        if ($end_month>12){
            $end_month = $end_month - 12;
            $end_year += 1;
        }
        $day_num_month = date('t', strtotime($end_year.'-'.$end_month));
        if ($end_day>$day_num_month){
            $end_day = $day_num_month;
        }
        $end_time = strtotime( $end_year.'-'.$end_month.'-'.$end_day.' '.$end_time );
        if ($end_time<=AC::SERVER_TIME){
            return false;
        }
        if ($addDay>0 && $addDay<365){
            //购买会员额外赠送时长天数
            $end_time += $addDay*3600*24;
        }
        $new = [
            'end_time' => $end_time, 'type' => 0
        ];
        $month==12 && $new['yearvip_end_time'] = $end_time;//年费会员
        if ($vip_info){
            //续费操作
            UK::saveLog($logs, date('Y-m-d H:i:s').':update:'.json_encode($new)."\n");
            $result = $this->autoUidModel->updateUserVipInfo($new, $uid);
        }else{
            //首次开通
            UK::saveLog($logs, date('Y-m-d H:i:s').':create:'.json_encode($new)."\n");
            $result = $this->autoUidModel->addUserVip($new, $uid);
        }
        if ($result){
            $result = $this->userModel->updateUserInfo(['uid'=>$uid], ['vip'=>$end_time], $uid);
            $result && $this->diaryListCacheModel->delUserCache($uid);
            if (empty($vip_info)){
                //首次开通增加会员流量
                $traffic = 200 * 1024;
                $trc_res = $this->userMemberModel->updateUserVipTraffic($uid, $traffic);
                $trc_res && UK::saveLog($logs, date('Y-m-d H:i:s').':traffic:'.$traffic."\n");
            }
        }
        UK::saveLog($logs, date('Y-m-d H:i:s').':result:'.$result."\n");
        return $result ? true : false;
    }

    /**
     * 获取内容中的大表情列表
     * @param $param
     * @return array|bool
     */
    public function getEmotionList($param)
    {
        $uid = isset($param['uid']) ? intval($param['uid']) : 0;
        $content = isset($param['content']) ? $param['content'] : '';
        if($uid < 1) {
            AC::$errorNo = "MBC004";
            return false;
        }
        if(empty($content)) {
            AC::$errorNo = "MBC005";
            return false;
        }
        $message = new MessageBoxController();
        return $message->getEmotionList($param);
    }

    public function backupMessage($param) {
        if (empty($param['uid'])) {
            AC::$errorNo    =   'RPC001';
            return  FALSE;
        }
        if(empty($param['message'])) {
            AC::$errorNo    =   'RPC002';
            return  FALSE;
        }
        if($param['type'] == 'message' && empty($param['toUid'])) {
            AC::$errorNo    =   'RPC005';       //私信必须有接收人
            return  FALSE;
        }
        if($param['type'] == 'groupMessage' && empty($param['toGid'])) {
            AC::$errorNo    =   'RPC006';       //群消息要有群id
            return  FALSE;
        }
        if($param['type'] == 'message') {
            return $this->addUserMessage($param);
        } else if ($param['type'] == 'groupMessage') {
            return $this->addGroupMessage($param);
        } else {
            AC::$errorNo    =   'RPC007';       //类型错误
            return  FALSE;
        }

    }

    public function addGroupMessage($param) {
        $userInfo = $this->autoUidModel->getUserInfo($param['uid']);

        if(empty($userInfo)) {
            AC::$errorNo    =   'RPC001';
            return  FALSE;
        }
        if(empty($param['message'])) {
            AC::$errorNo    =   'RPC002';
            return  FALSE;
        }
        $group = $this->likeModel->getChatGroupInfoByGid($param['toGid']);
        if (empty($group)){
            AC::$errorNo = 'RPC006';
            return  FALSE;
        }
        // 查询在群中信息
        $linkInfo = $this->likeModel->getGroupUserLinkInfo($param['uid'], $param['toGid'], AC::CHAT_GROUP_PASS_STATUS);
        if (empty($linkInfo)){
            AC::$errorNo = 'LGC011';
            return FALSE;
        }
//        $chatUserInfo = $this->likeModel->getChatUserInfoById($param['uid'], $linkInfo, $group);
        $message = UK::parseData($param['message']);
        $message['uid'] = $param['uid'];

        // 写入数据库数据
        $info = array(
            'uid'      =>    $param['uid'],
            'gid'      =>    $param['toGid'],
            'nickname' =>    $userInfo['nickname'],
            'device'   =>    '',
            'content'  =>    isset($message['content']) ? $message['content'] : '',
            'msgType'  =>    isset($message['msgType']) ? $message['msgType'] : '',
            'time'     =>    isset($message['time']) ? $message['time'] : 0,
            'msgData'  =>    ''
        );

        // 处理分享数据
        if ($message['msgType'] == 'share' && !empty($message['data'])) {
            $share = [
                'data_action'   =>  $message['data']['action'],
                'data_title'   =>  $message['data']['title'],
                'data_image'   =>  $message['data']['image'],
                'data_content'   =>  $message['data']['content']
            ];
            $topicShareData = $this->topicModel->structureTopicShareData($share);
            if (!empty(AC::$errorNo)) {
                UK::varDump(AC::$errorNo, __METHOD__);
                return  FALSE;
            }
            $info['msgType'] = $topicShareData['msgType'];
            $info['msgData'] = $topicShareData['msgData'];
        }

        $id =   $this->likeModel->postGroupChat($info);

        // 附件判断
        $is_attachment = FALSE;
        $is_voice      = FALSE;
        $message['attachment'] = $this->rebuildAttachment($message['attachment']);
        $message['voice'] = $this->rebuildAttachment($message['voiceList']);

        if (is_array($message['attachment'])  &&  count($message['attachment']) > 0){
            $is_attachment = TRUE;
        }
        if (is_array($message['voice'])  &&  count($message['voice']) >  0){
            $is_voice = TRUE;
        }
        $message_id = 0;
        if ($is_attachment || $is_voice){
            $key           =    'GCM/'.$param['toGid'];
            $message_id    =    UK::getBodyidByItemid($key, $id);
        }

        // 默认为图片附件
        if ($is_attachment){
            $attachments = array_slice($message['attachment'], 0, 1);
            $tmpInfo    =   array(
                'uid'               =>  $param['toGid'],
                'bodyId'            =>  1,
                'attachment'        =>  $attachments,
                'attachment_type'   =>  1,
                'type'              =>  4,
                'type_id'           =>  $message_id,
                'rpc'               =>  1
            );
            $this->diaryAttachmentModel->addDiaryAttachment($tmpInfo);
        }
        // 语音附件
        if ($is_voice){
            $voices = array_slice($message['voice'], 0, 1);
            $voiceInfo    =   array(
                'uid'               =>  $param['toGid'],
                'bodyId'            =>  1,
                'attachment'        =>  $voices,
                'attachment_type'   =>  2,
                'type'              =>  4,
                'type_id'           =>  $message_id,
                'rpc'               =>  1
            );
            $this->diaryAttachmentModel->addDiaryAttachment($voiceInfo);
        }
        $result = (Object) array();
        // 返回聊天列表
        if ($id)
        {
            // 返回该条记录
            $chatMessageInfo              =    $info;
            $chatMessageInfo['id']        =    $id;
            $userInfo                     =    $this->autoUidModel->getUserInfo($param['uid']);
            $chatMessageInfo['avatar']    =    $userInfo['avatar'];
            $chatMessageInfo              =    $this->chatGroupService->structureChatMessageData($chatMessageInfo);

            if (!empty($chatMessageInfo)){
                $result = $chatMessageInfo;
            }

            // 更新最后发言时间
            $data = array('last_time' => AC::SERVER_TIME);
            $this->likeModel->setGroupUserData($param['uid'], $linkInfo['linkid'], $data, $param['toGid']);
        }
        $result['user'] = [
            'uid' => $userInfo['uid'],
            'nickname'  => $userInfo['nickname'],
            'avatar'    => $userInfo['avatar']
        ];
        $result['group'] = [
            'gid'   =>  $group['gid'],
            'cover' =>  $group['cover'],
            'name'  =>  $group['name']
        ];
        return  $result;

    }

    private function rebuildAttachment($attachment) {
        if(empty($attachment)) return $attachment;
        $result = array();
        foreach ($attachment as $value) {
            $tmp = [
                'path' => $value['attachmentPath'],
                'info' => $value['info']
            ];
            $result[] = $tmp;
        }
        return $result;
    }

    /**
     * 保存IM信息
     * @param $param
     * @return bool
     */
    public function addUserMessage($param) {

        $userInfo = $this->autoUidModel->getUserInfo($param['uid']);
        $mUidBaseInfo = $this->autoUidModel->getUserInfo($param['toUid']);

        if(empty($userInfo) || empty($mUidBaseInfo)) {
            AC::$errorNo    =   'RPC001';
            return  FALSE;
        }
        if(empty($param['message'])) {
            AC::$errorNo    =   'RPC002';
            return  FALSE;
        }
        $message = UK::parseData($param['message']);
        $message['uid'] = $param['uid'];
        $message['mUid'] = $param['toUid'];
        // 发送私信的数据
        $data = array(
            'uid'      =>    $param['uid'],
            'mUid'     =>    $param['toUid'],
            'nickname' =>    $userInfo['nickname'],
            'mNickname'=>    $mUidBaseInfo['nickname'],
            'content'  =>    isset($message['content']) ? $message['content'] : '',
            'msgType'  =>    isset($message['msgType']) ? $message['msgType'] : '',
            'time'     =>    isset($message['time']) ? $message['time'] : 0
        );

        // 分页可能需要
        isset($message['id'])    &&    $data['id']    =    $message['id'];

        // 处理分享数据
        if ($message['msgType'] == 'share' && !empty($message['data'])) {
            $share = [
                'data_action'   =>  $message['data']['action'],
                'data_title'   =>  $message['data']['title'],
                'data_image'   =>  $message['data']['image'],
                'data_content'   =>  $message['data']['content']
            ];
            $topicShareData = $this->topicModel->structureTopicShareData($share);
            if (!empty(AC::$errorNo)) {
                UK::varDump(AC::$errorNo, __METHOD__);
                return  FALSE;
            }
            $data['msgType'] = $topicShareData['msgType'];
            $data['msgData'] = $topicShareData['msgData'];
        }

        // 附件判断
        $attachment = FALSE;
        $voice      = FALSE;
        $message['attachment'] = $this->rebuildAttachment($message['attachment']);
        $message['voice'] = $this->rebuildAttachment($message['voiceList']);
        if (is_array($message['attachment'])  &&  count($message['attachment']) > 0){
            $attachment = TRUE;
        }
        if (is_array($message['voice'])  &&  count($message['voice']) >  0){
            $voice = TRUE;
        }
        $messageInfo = $this->messageBoxModel->addMessage($data, $attachment, $voice);

        if (empty($messageInfo)){
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }

        // 存储图片
        $this->addMessageAttachment ($message, $messageInfo['last_attachment']);

        $result = $this->messageService->rebuildData($messageInfo);
        $result['user'] = [
            'uid' => $userInfo['uid'],
            'nickname'  => $userInfo['nickname'],
            'avatar'    => $userInfo['avatar']
        ];
        return $result;
    }

    private function addMessageAttachment ($info, $type_id) {
        if (AC::$errorNo) return false;

        $info['type']    = 3;
        $info['bodyId']  = 1;
        $info['type_id'] = $type_id;

        $userService = new UserService();
        $user = $userService->getUserInfo($info['uid'], $info['uid']);

        $attachmentService = new AttachmentService();

        $attachmentService->saveDiaryAttachment($info, $user);

        AC::$errorNo = '';
        return true;
    }

    /**
    *   创建会员订单(ios单月自动续订)
    */
    public function createVipOrder($param){
        $data = [];
        $data['uid'] = $param['uid'];
        $data['sn']  = 'vip'.$this->getRandChar(15);
        $data['goods_id']  = 13;
        $data['goods_amount']  = 10;
        $data['goods_num']  = 1;
        $data['goods_title']  = '1个月粉粉会员';
        $data['order_amount']  = 1000;
        $data['create_time']  = AC::SERVER_TIME;
        $data['update_time']  = AC::SERVER_TIME;
        $data['third_order']  = isset($param['third_order']) ? $param['third_order'] : '';
        $data['third_type']  = 1;
        $data['third_extend']  = '{"apple":""}';
        $data['channel']  = 'apple';
        $data['pay_status']  = 1;
        $data['order_status']  = 4;
        $data['platform']  = 1;
        $data['source']  = 'activity20170606';
        return $this->userMemberModel->addUserVipOrder($data);
    }

    private function getRandChar( $length ) {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $password = "";
        for ( $i = 0; $i < $length; $i++ )
        {
            $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        }
        return $password;
    }

    //发送文章,即将文章相关点滴由私密转公开
    public function editDiary($param)
    {
        $info = $this->diaryListModel->getDiaryInfoByBodyId($param['bodyId']);
        if (empty($info)) {
            return false;
        }
        if($info['secret'] == $param['secret']) {
            return true;
        }
        $param['uid'] = $info['uid'];
        $this->diaryListModel->setDiaryList($param);
        $this->diaryBodyModel->setDiaryBody($param);
        if (!empty(AC::$errorNo)) {
            return false;
        }
        #redis 修改日志时删除旧的缓存,将新数据加入缓存
        $this->diaryListCacheModel->delDiaryCache($param['bodyId']);
        $this->diaryListModel->getDiaryInfoByBodyId($param['bodyId']);
        $secret = 0;
        if (!empty($param['secret'])) $secret = 1;
        if ($info['secret'] != $secret) {
            $statistics = $this->userStatisticsModel->getUserStatistics(array('uid' => $info['uid']));
            $data['uid'] = $param['uid'];
            if (1 == $secret) {
                $data['diaryTimes'] = $statistics['diaryTimes'] - 1;
                $data['secretDiaryTimes'] = $statistics['secretDiaryTimes'] + 1;
                $this->diaryListCacheModel->delDiarySquare($info);
            } else {
                $data['diaryTimes'] = $statistics['diaryTimes'] + 1;
                $data['secretDiaryTimes'] = $statistics['secretDiaryTimes'] - 1;
            }
            if ($data['diaryTimes'] < 1) $data['diaryTimes'] = 0;
            if ($data['secretDiaryTimes'] < 1) $data['secretDiaryTimes'] = 0;
            $this->userStatisticsModel->setUserStatistics($data);
        }
        return true;
    }
}